package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowow.comment.domain.TravelComment;
import cn.wolfcode.luowow.comment.query.TravelCommentQuery;
import cn.wolfcode.luowow.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.comment.repository.ITravelCommentRepository;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService{

    @Autowired
    private ITravelCommentRepository repository; //crud操作

    @Autowired
    private MongoTemplate template;  //高级查询

    @Override
    public TravelComment saveOrUpdate(TravelComment comment) {

        //添加跟更新
        if(!StringUtils.hasLength(comment.getId())){
            comment.setCreateTime(new Date());
        }

        //需要处理引用的评论
        if(comment.getType() == TravelComment.TRAVLE_COMMENT_TYPE){
            if(StringUtils.hasLength(comment.getRefComment().getId())){
                comment.setRefComment(repository.findById(comment.getRefComment().getId()).get());
            }
        }
        repository.save(comment);
        return comment;
    }

    @Override
    public Page query(TravelCommentQuery qo) {
        //需要查询评论列表并分页显示,而且目前有的api无法直接得到分页对象Page
        //只能通过之前的高级查询时候弄个pageResult,总结封装Page对象

        Query query = new Query();

        //查询条件
        if(qo.getTravelId() !=-1){
            query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        }

        //第一个参数是当前页,因为是从0开始的,所以我们要-1,第二个是页面大小,第三个是排序,第四个是排序的列
       Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.DESC,"createTime");

        //查询总数
        Long total = template.count(query,TravelComment.class);

        if(total == null){
            return Page.empty();
        }

        //查询当前显示页数
        List<TravelComment> list = template.find(query, TravelComment.class);

        //返回 的是一个分页的,因为是一个接口的,所有我们要new一个实现类出来返回,分页内容还没有,先不要管
        return new PageImpl(list,pageable,total);

    }

    @Override
    public long getCount(Long travelId) {

        Query query = new Query();

        //查询条件
        query.addCriteria(Criteria.where("travelId").is(travelId));

        //查总数
        return template.count(query,TravelComment.class);
    }
}
